package fr.afcepf.ticketing.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class GenericDaoJpa<T, T2> implements GenericDao<T, T2> {

	private Class<T> persistantClass;
	@PersistenceContext
	
	private EntityManager entityManager;

	public GenericDaoJpa() {
		initPersistanceClass();
	}

	private void initPersistanceClass() {

		try {
			ParameterizedType parameterizedType = (ParameterizedType) getClass()
					.getGenericSuperclass();
			Type typeT = parameterizedType.getActualTypeArguments()[0];
			if (!typeT.toString().equals("T"))
				this.persistantClass = (Class<T>) typeT;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Override
	public T getEntityByPk(Object pk) {
		return (T) entityManager.find(persistantClass, pk);
	}

	@Override
	public void updateEntity(T entity) {
		entityManager.merge(entity);

	}

	@Override
	public T2 createEntity(T entity) {
		entityManager.persist(entity);
		return null;
	}

	@Override
	public void deleteEntityFromPk(T2 pk) {
		entityManager.remove(this.getEntityByPk(pk));

	}

}
